package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hy.corecode.idgen.WFGIdGenerator;
import io.xxx.xbutler.data.ContactMapper;
import io.xxx.xbutler.data.RoomContactMapper;
import io.xxx.xbutler.data.RoomMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.Contact;
import io.xxx.xbutler.domain.Room;
import io.xxx.xbutler.domain.RoomContact;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 新成员入群回调接口（兼容PC）
 * <p>
 * 群内有新人加入，通过该接口将新人入群信息回调给商家
 * <pre>
 * {
 *     "Data": {
 *         "Members": [
 *             {
 *                 "vcNickName": "XhT",
 *                 "vcFatherWxId": "wxid_bysnjh4y1f1922",
 *                 "vcHeadImgUrl": "https://wx.qlogo.cn/mmhead/ver_1/IWQBJb7gbCSRf0xENCws4527iaqXYQj2539lrZMDu0LuBkMSW6zZymibCk1TBOfty6iau5ECrmxTMqWfB47o71Qj70GPV706vlaXJpcaFFJDbWJzqPQuQhQHicg1v4EO73wu/132",
 *                 "vcGroupNickName": "",
 *                 "vcBase64NickName": "WGhU",
 *                 "vcMemberUserWxId": "wxid_ovcy2qndk7fq22",
 *                 "IsEnterpriseChatroom": false,
 *                 "vcMemberUserSerialNo": "6960BD572AD1AC48C30C2B7D1CC46BC5",
 *                 "vcBase64GroupNickName": "",
 *                 "vcFatherWxUserSerialNo": "DA1B048A0F72A1142FE1F29C982E3B79"
 *             }
 *         ],
 *         "nMemberCount": 14,
 *         "vcChatRoomId": "57837592466@chatroom",
 *         "nChatRoomIsOpen": 1,
 *         "vcChatRoomSerialNo": "D3138867BDFEBFD1477320B3DF58082A"
 *     },
 *     "nType": 4502,
 *     "nResult": 1,
 *     "vcResult": "SUCCESS",
 *     "nTimeStamp": 1738831673956,
 *     "vcSerialNo": "20250206164753696149216756916",
 *     "vcRobotWxId": "wxid_bygdfjr4t4se22",
 *     "vcMerchantNo": "202407150008480",
 *     "vcRobotSerialNo": "C6FE5DA5A713ECA14149E433DA3323EC"
 * }
 * </pre>
 */
@Slf4j
@Component
public class _4502Handler implements CallbackHandler {

    @Resource
    private WFGIdGenerator idGenerator;

    @Resource
    private RoomMapper roomMapper;

    @Resource
    private ContactMapper contactMapper;

    @Resource
    private RoomContactMapper roomContactMapper;

    @Override
    public String name() {
        return "新成员入群回调";
    }

    @Override
    public boolean supports(int type) {
        return type == 4502;
    }

    @Override
    public void handle(Callback callback) {
        LocalDateTime now = LocalDateTime.now();

        JSONObject data = (JSONObject) callback.getData();
        String roomId = data.getString("vcChatRoomId");
        Room room = roomMapper.selectById(roomId);
        if (room == null) {
            log.error("群信息不存在[serialNo:{}, robotId:{}, robotSerialNo:{}, roomId:{}]",
                    callback.getSerialNo(), callback.getRobotId(), callback.getRobotSerialNo(), roomId);
            return;
        }

        String roomSerialNo = data.getString("vcChatRoomSerialNo");
        Integer memberCount = data.getInteger("nMemberCount");
        LambdaUpdateWrapper<Room> roomWrapper = new LambdaUpdateWrapper<Room>()
                .set(Room::getMemberCount, memberCount)
                .set(Room::getUpdatedTime, now)
                .eq(Room::getId, roomId);
        roomMapper.update(roomWrapper);

        JSONArray members = data.getJSONArray("Members");
        for (Object o : members) {
            JSONObject member = JSONObject.from(o);
            String contactId = member.getString("vcMemberUserWxId");
            Contact contact = new Contact()
                    .setId(contactId)
                    .setSerialNo(member.getString("vcMemberUserSerialNo"))
                    .setName(member.getString("vcNickName"))
                    .setBase64Name(member.getString("vcBase64NickName"))
                    .setAvatar(member.getString("vcHeadImgUrl"))
                    .setRemarkName(member.getString("vcRemarkName"))
                    .setBase64RemarkName(member.getString("vcBase64RemarkName"));
            boolean contactExists = isExists(contactId);
            if (!contactExists) {
                contactMapper.insert(contact);
            } else {
                contactMapper.updateById(contact);
            }

            boolean roomContactExists = isExists(roomId, contactId);
            if (!roomContactExists) {
                RoomContact roomContact = new RoomContact()
                        .setId(idGenerator.next())
                        .setRoomId(roomId)
                        .setRoomSerialNo(roomSerialNo)
                        .setContactId(contact.getId())
                        .setContactSerialNo(contact.getSerialNo())
                        .setContactName(member.getString("vcGroupNickName"))
                        .setBase64ContactName(member.getString("vcBase64GroupNickName"))
                        .setInventorId(member.getString("vcFatherWxId"))
                        .setInventorSerialNo(member.getString("vcFatherWxUserSerialNo"))
                        .setCreatedTime(now);
                roomContactMapper.insert(roomContact);
            } else {
                LambdaUpdateWrapper<RoomContact> wrapper = new LambdaUpdateWrapper<RoomContact>()
                        .set(RoomContact::getContactName, member.getString("vcGroupNickName"))
                        .set(RoomContact::getBase64ContactName, member.getString("vcBase64GroupNickName"))
                        .set(RoomContact::getUpdatedTime, now)
                        .eq(RoomContact::getRoomId, roomId)
                        .eq(RoomContact::getContactId, contact.getId());
                roomContactMapper.update(wrapper);
            }
        }
    }

    private boolean isExists(String contactId) {
        LambdaQueryWrapper<Contact> wrapper = new LambdaQueryWrapper<Contact>()
                .eq(Contact::getId, contactId);
        return contactMapper.exists(wrapper);
    }

    private boolean isExists(String roomId, String contactId) {
        LambdaQueryWrapper<RoomContact> wrapper = new LambdaQueryWrapper<RoomContact>()
                .eq(RoomContact::getRoomId, roomId)
                .eq(RoomContact::getContactId, contactId);
        return roomContactMapper.exists(wrapper);
    }
}
